package com.wn.demo01;


import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yellow Docter
 * @date 2022 -11-08
 * @desc 通过jwt 创建一个token
 */
public class Demo01 {

    public static void main(String[] args) {

        //01 创建 一个载荷
        Map<String, Object> playLoad = new HashMap<>();
        playLoad.put("name", "admin");
        playLoad.put("userId", "101");

        //02 创建签名器 (通过载体和签名 可以创建一个token)

        //keyPair 通过工厂创建
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(
                new ClassPathResource("jwt.jks"),
                "123456".toCharArray()
        );

        // 密钥对
        KeyPair keyPair = factory.getKeyPair("jwt");
        JWTSigner signer = JWTSignerUtil.createSigner("RSA", keyPair);

        //通过 载体 和 signer 创建一个token
        String token = JWTUtil.createToken(playLoad, signer);
        System.out.println("token = " + token);

        // token的认证
        //通过token 字符串 和
        // JWTSigner 进行认证
//        boolean aaa = JWTUtil.verify("a.a.a", signer);
//        System.out.println("aaa = " + aaa);

        boolean verify = JWTUtil.verify(token, signer);
        System.out.println("verify = " + verify);

        //解析token
        if (verify) {

            //解析token
            JWT jwt = JWTUtil.parseToken(token);
            Object name = jwt.getPayload("name");
            System.out.println("name = " + name);
            Object userId = jwt.getPayload("userId");
            System.out.println("userId = " + userId);

        }

    }

}
